package cn.mysite.mycompany.mapper;

import cn.mysite.mycompany.fabricSDK.FabricClient;
import cn.mysite.mycompany.fabricSDK.User;
import cn.mysite.mycompany.fabricSDK.UserContext;
import cn.mysite.mycompany.fabricSDK.UserUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.hyperledger.fabric.sdk.Enrollment;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.TransactionRequest;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.exception.TransactionException;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class FUserMapper {

    private static final String keyFolderPath = "E:\\CodeBase\\Java\\ShopMall\\src\\main\\resources\\crypto-config\\peerOrganizations\\org2.example.com\\users\\Admin@org2.example.com\\msp\\keystore";
    private static final String keyFileName="38f0ea6ae239210010c59f5242b2f92dd2657de0f74cc5a2a5d0966208235fea_sk";
    private static final String certFoldePath="E:\\CodeBase\\Java\\ShopMall\\src\\main\\resources\\crypto-config\\peerOrganizations\\org2.example.com\\users\\Admin@org2.example.com\\msp\\admincerts";
    private static final String certFileName="Admin@org2.example.com-cert.pem";
    private static  final String tlsOrderFilePath = "E:\\CodeBase\\Java\\ShopMall\\src\\main\\resources\\crypto-config\\ordererOrganizations\\example.com\\tlsca\\tlsca.example.com-cert.pem";
    private static final String txfilePath = "E:\\CodeBase\\Java\\fabric\\src\\main\\resources\\test.tx";
    private static  final String tlsPeerFilePath = "E:\\CodeBase\\Java\\ShopMall\\src\\main\\resources\\crypto-config\\peerOrganizations\\org1.example.com\\msp\\tlscacerts\\tlsca.org1.example.com-cert.pem";
    private static  final String tlsPeerFilePathAddtion = "E:\\CodeBase\\Java\\ShopMall\\src\\main\\resources\\crypto-config\\peerOrganizations\\org2.example.com\\tlsca\\tlsca.org2.example.com-cert.pem";

    private FabricClient fabricClient;

    public FUserMapper() throws IllegalAccessException, InvalidArgumentException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, CryptoException, InvalidKeySpecException, NoSuchAlgorithmException, org.bouncycastle.crypto.CryptoException, IOException {
        UserContext userContext = new UserContext();
        userContext.setAffiliation("Org2");//设置组织
        userContext.setMspId("Org2MSP");//
        userContext.setAccount("李伟");
        userContext.setName("admin");
        Enrollment enrollment =  UserUtils.getEnrollment(keyFolderPath,keyFileName,certFoldePath,certFileName);
        userContext.setEnrollment(enrollment);//设置用户证书
        fabricClient = new FabricClient(userContext);

    }

    public User getOne() throws InvalidArgumentException, ProposalException, TransactionException {
        Peer peer0 = fabricClient.getPeer("peer0.org1.example.com","grpcs://peer0.org1.example.com:7051",tlsPeerFilePath);
        //Peer peer1 = fabricClient.getPeer("peer0.org2.example.com","grpcs://peer0.org2.example.com:7051",tlsPeerFilePathAddtion);
        List<Peer> peers = new ArrayList<>();
        peers.add(peer0);
        //peers.add(peer1);
        String initArgs[] = {"hyid002"};
        Map map =  fabricClient.queryChaincode(peers,"mychannel", TransactionRequest.Type.GO_LANG,"hyxxcc","queryHyxx",initArgs);
        System.out.println(StringUtils.strip(map.values().toString(),"[]"));
        User user= JSON.parseObject(StringUtils.strip(map.values().toString(),"[]"),User.class);
        return user;
    }

    public boolean save() throws InvalidArgumentException, ProposalException, TransactionException {
        Peer peer0 = fabricClient.getPeer("peer0.org1.example.com","grpcs://peer0.org1.example.com:7051",tlsPeerFilePath);
       // Peer peer1 = fabricClient.getPeer("peer0.org2.example.com","grpcs://peer0.org2.example.com:7051",tlsPeerFilePathAddtion);
        Orderer order = fabricClient.getOrderer("orderer.example.com","grpcs://orderer.example.com:7050",tlsOrderFilePath);
        List<Peer> peers = new ArrayList<>();
        peers.add(peer0);
        //peers.add(peer1);
        String initArgs[] = {"hyid002"};
        fabricClient.invoke("mychannel",TransactionRequest.Type.GO_LANG,"hyxxcc",order,peers,"queryHyxx",initArgs);
        return false;
    }
    public boolean save(cn.mysite.mycompany.entity.User user)throws InvalidArgumentException, ProposalException, TransactionException {
        Peer peer0 = fabricClient.getPeer("peer0.org1.example.com","grpcs://peer0.org1.example.com:7051",tlsPeerFilePath);
        // Peer peer1 = fabricClient.getPeer("peer0.org2.example.com","grpcs://peer0.org2.example.com:7051",tlsPeerFilePathAddtion);
        Orderer order = fabricClient.getOrderer("orderer.example.com","grpcs://orderer.example.com:7050",tlsOrderFilePath);
        List<Peer> peers = new ArrayList<>();
        peers.add(peer0);
        //peers.add(peer1);
        String initArgs[] = {user.getId().toString(),user.getLoginName(),user.getUserName(),user.getPassword(),user.getGendercode().toString(),user.getIdentityCode(), user.getEmail(), user.getMobile(),user.getFileName()};
        try{
        fabricClient.invoke("mychannel",TransactionRequest.Type.GO_LANG,"user9",order,peers,"insertUser",initArgs);
        }
        catch (Exception e){
            return false;
        }
        return true;
    }
    public cn.mysite.mycompany.entity.User getOne(String loginname,String password) throws InvalidArgumentException, ProposalException, TransactionException {
        Peer peer0 = fabricClient.getPeer("peer0.org1.example.com","grpcs://peer0.org1.example.com:7051",tlsPeerFilePath);
        //Peer peer1 = fabricClient.getPeer("peer0.org2.example.com","grpcs://peer0.org2.example.com:7051",tlsPeerFilePathAddtion);
        List<Peer> peers = new ArrayList<>();
        peers.add(peer0);
        //peers.add(peer1);
        String initArgs[] = {loginname,password};

        Map map = fabricClient.queryChaincode(peers, "mychannel", TransactionRequest.Type.GO_LANG, "user9", "queryPassword", initArgs);


        //int id =Integer.parseInt(StringUtils.strip(map.values().toString(),"[]"));
        //initArgs= new String[]{StringUtils.strip(map.values().toString())};
        //Map usermap=fabricClient.queryChaincode(peers, "", TransactionRequest.Type.GO_LANG, "user8", "queryUser", initArgs);
        if(map.containsKey(500))
            return null;
        String userString=StringUtils.strip(map.values().toString(),"[]");
        cn.mysite.mycompany.entity.User user=JSON.parseObject(userString,cn.mysite.mycompany.entity.User.class);
        //性别为什么没赋值
        return user;
    }

}
